package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Articles;
import com.example.entity.ArticlesLike;
import com.example.mapper.ArticlesLikeMapper;
import com.example.mapper.ArticlesMapper;
import com.example.mapper.UnionMapper;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * The type Articles service.
 */
@Service
public class ArticlesService {
    @Autowired
    private ArticlesMapper mapper;
    @Autowired
    private UnionMapper unionMapper;
    @Autowired
    private ArticlesLikeMapper articlesLikeMapper;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * Gets board.
     *
     * @param articles the articles
     * @return the board
     */
    public ResultData getBoard(Articles articles) {
        if (articles.getPage() != null) {
            QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_examine", 1);
            queryWrapper.orderByDesc("article_views");
            Page<Articles> pages = new Page<>(articles.getPage(), 6);
            IPage<Articles> result = mapper.selectPage(pages, queryWrapper);
            if (!result.getRecords().isEmpty()) {
                return ResultUtils.sucuss("查询成功", result);
            } else {
                return ResultUtils.error("查询失败", result);
            }
        } else {
            throw new BisException("页码不能为空");
        }
    }

    /**
     * Gets examine.
     *
     * @return the examine
     */
    public ResultData getExamine() {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_examine", 0);
        queryWrapper.orderByDesc("article_id");
        List<Articles> result = mapper.selectList(queryWrapper);
        if (result.isEmpty()) {
            throw new BisException("暂无待审核文章");
        } else {
            return ResultUtils.sucuss("查询成功", result);
        }
    }

    /**
     * Sets examine row.
     *
     * @param articles the articles
     * @return the examine row
     */
    public ResultData setExamineRow(Articles articles) {
        UpdateWrapper<Articles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("article_id", articles.getArticleId());
        updateWrapper.set("article_examine", 1);
        int result = mapper.update(null, updateWrapper);
        if (result == 0) {
            throw new BisException("文章审核失败");
        } else {
            return ResultUtils.sucuss("文章审核成功", result);
        }
    }

    /**
     * Gets label all.
     *
     * @return the label all
     */
    public ResultData getLabelALL() {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("distinct article_classification");
        queryWrapper.eq("article_examine", 1);
        List<Articles> result = mapper.selectList(queryWrapper);
        if (result.isEmpty()) {
            return ResultUtils.error("还没有标签！！", null);
        } else {
            return ResultUtils.sucuss("查询成功！！", result);
        }
    }

    /**
     * Gets label.
     *
     * @param articles the articles
     * @return the label
     */
    public ResultData getLabel(Articles articles) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_classification", articles.getArticleClassification()).orderByDesc("article_date");
        List<Articles> result = mapper.selectList(queryWrapper);
        if (result.isEmpty()) {
            return ResultUtils.error("无此标签，查询失败！", null);
        } else {
            return ResultUtils.sucuss("标签查询成功", result);
        }
    }

    /**
     * Add board result data.
     *
     * @param file     the file
     * @param articles the articles
     * @return the result data
     */
    public ResultData addBoard(MultipartFile file, Articles articles) {
        //判断文件不为空
        if (!file.isEmpty()) {
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String suffixName = fileName.substring(fileName.indexOf("."));
            //重新生成文件名
            String md5Name = DigestUtils.md5DigestAsHex(fileName.getBytes());
            String filename = md5Name + suffixName;
            //指定本地存入路径
            String filePath = "/www/admin/www.xinggaoya.com_80/wwwroot/blog/picture/";
            String LinuxPath = filePath + filename;
            try {
                file.transferTo(new File(LinuxPath));
                Runtime.getRuntime().exec("chmod 777 -R " + LinuxPath);
                String MysqlName = "http://www.xinggaoya.com/blog/picture/" + filename;
                articles.setArticleImg(MysqlName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultUtils.error("文件上传失败", null);
            }
        } else {
            System.out.println("文件是空的");

        }
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf3.format(new Date());
        articles.setArticleDate(date);
        int resultList = mapper.insert(articles);
        if (resultList <= 0) {
            return ResultUtils.error("文章发表失败", resultList);
        } else {
            return ResultUtils.sucuss("文章发表成功,待管理员审核！", resultList);
        }
    }

    /**
     * Gets boardbyid.
     *
     * @param articles the articles
     * @return the boardbyid
     */
    public ResultData getBoardbyid(Articles articles) {

        Articles result = mapper.selectById(articles.getArticleId());
        List<Articles> list = unionMapper.getArticleLike(articles);
        if (result != null) {
            if (redisUtils.get(articles.getUserName() + articles.getArticleId()) == null) {
                result.setArticleViews(result.getArticleViews() + 1);
                redisUtils.set(articles.getUserName() + articles.getArticleId(), 1, 1800);
            }
            result.setArticleLikeCount(list.size());
            mapper.updateById(result);
            return ResultUtils.sucuss("查询成功", result);
        } else {
            return ResultUtils.error("查询失败", result);
        }
    }

    /**
     * Gets board by user.
     *
     * @param articles the articles
     * @return the board by user
     */
    public ResultData getBoardByUser(Articles articles) {

        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", articles.getUserName()).orderByDesc("article_date");
        List<Articles> result = mapper.selectList(queryWrapper);
        if (!result.isEmpty()) {
            return ResultUtils.sucuss("查询成功", result);
        } else {
            throw new BisException("查询失败");
        }
    }

    /**
     * Add board like result data.
     *
     * @param articlesLike the articles like
     * @return the result data
     */
    public ResultData addBoardLike(ArticlesLike articlesLike) {
        QueryWrapper<ArticlesLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articlesLike.getArticleId());
        if (!String.valueOf(articlesLike.getArticleId()).isEmpty()) {
            int result = articlesLikeMapper.insert(articlesLike);
            if (result > 0) {
                return ResultUtils.sucuss("点赞成功", result);
            } else {
                return ResultUtils.error("点赞失败", result);
            }
        } else {
            return ResultUtils.error("缺少博客标识", null);
        }
    }

    /**
     * Del board like result data.
     *
     * @param articlesLike the articles like
     * @return the result data
     */
    public ResultData DelBoardLike(ArticlesLike articlesLike) {
        QueryWrapper<ArticlesLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", articlesLike.getArticleId());
        queryWrapper.eq("user_name", articlesLike.getUserName());
        int result = articlesLikeMapper.delete(queryWrapper);
        if (result > 0) {
            return ResultUtils.sucuss("取消点赞成功", result);
        } else {
            return ResultUtils.error("点赞失败", result);
        }
    }

    /**
     * Board byuser result data.
     *
     * @param articlesLike the articles like
     * @return the result data
     */
    public ResultData BoardByuser(ArticlesLike articlesLike) {
        QueryWrapper<ArticlesLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", articlesLike.getUserName());
        queryWrapper.eq("article_id", articlesLike.getArticleId());
        List<ArticlesLike> result = articlesLikeMapper.selectList(queryWrapper);
        if (!result.isEmpty()) {
            return ResultUtils.error("已点赞", result);
        } else {
            return ResultUtils.sucuss("无点赞", result);
        }
    }

    /**
     * Delete byid result data.
     *
     * @param articles the articles
     * @return the result data
     */
    public ResultData deleteByid(Articles articles) {

        if (!String.valueOf(articles.getArticleId()).isEmpty()) {
            int result = mapper.deleteById(articles.getArticleId());
            if (result > 0) {
                return ResultUtils.sucuss("删除成功！", result);
            } else {
                return ResultUtils.error("删除失败!", null);
            }
        } else {
            throw new BisException("缺少必要因素");
        }
    }

    /**
     * Update articles result data.
     *
     * @param articles the articles
     * @param file     the file
     * @return the result data
     */
    public ResultData updateArticles(Articles articles, MultipartFile file) {

        //判断文件不为空
        if (!file.isEmpty()) {
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String suffixName = fileName.substring(fileName.indexOf("."));
            //重新生成文件名
            String md5Name = DigestUtils.md5DigestAsHex(fileName.getBytes());
            String filename = md5Name + suffixName;
            //指定本地存入路径
            String filePath = "/www/admin/www.xinggaoya.com_80/wwwroot/blog/picture/";
            String LinuxPath = filePath + filename;
            try {
                file.transferTo(new File(LinuxPath));
                Runtime.getRuntime().exec("chmod 777 -R " + LinuxPath);
                String MysqlName = "http://www.xinggaoya.com/blog/picture/" + filename;
                articles.setArticleImg(MysqlName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultUtils.error("文件上传失败", null);
            }
        }

        if (!String.valueOf(articles.getArticleId()).isEmpty()) {
            int result = mapper.updateById(articles);
            if (result > 0) {
                return ResultUtils.sucuss("更新成功！，待管理员审核。", result);
            } else {
                return ResultUtils.error("更新失败！", null);
            }
        } else {
            return ResultUtils.error("缺少必要条件", null);
        }

    }

}
